#include "dump_auxv.h"

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

int main(void) {
    dump_auxv();
    printf("Begin forking\n");

    pid_t child = fork();
    if (child == -1) {
        perror("Failed to create a child by fork");
        return EXIT_FAILURE;
    } else if (child == 0) {
        dump_auxv();
        char bin_path[] = "./printf_test";
        char *const argv[] = { bin_path, NULL };
        if (execv(bin_path, argv) == -1) {
            int last_error = errno;
            fprintf(stderr,
                "Failed to reload process image '%s' by execv: %s\n",
                bin_path, strerror(last_error));
            return EXIT_FAILURE;
        }
    } else {
        int status;
        pid_t pid = waitpid(child, &status, 0);
        if (pid == -1) {
            int last_error = errno;
            fprintf(stderr,
                "Failed to wait for status of process %ld by waitpid: %s\n",
                (long) child, strerror(last_error));
            return EXIT_FAILURE;
        }
        printf("Child process %ld has exited\n", (long) child);
    }

    return EXIT_SUCCESS;
}
